<?php
class AjaxModule
{
	function index() {

	}
	
	function comment(){
		global $_G;
		$id = empty($_GET['id']) ? 0 : intval($_GET['id']);
		$action = isset($_GET['a'])?$_GET['a']:null;
		switch ($action){
			case 'add':
					$errmsg = $output = $comment = array();
					$comment['uid'] = 0;
					$comment['referid'] = getGP('aid','P','int');
					$comment['shopid'] = getGP('shopid','P','int');
					$comment['pid'] = getGP('pid','P','int');
					$comment['type'] = getGP('type','P','int');
					$comment['username'] = getGP('username','P');
					$comment['email'] = strtolower(getGP('email','P'));
					$comment['content'] = preg_replace(array("/(\r\n){3,}/","/(\r){3,}/","/(\n){3,}/"),array("\${1}","\${1}","\${1}"),getGP('content','P'));
					$comment['content'] = nl2br(check_str($comment['content']));
					$comment['ishide'] = (getGP('hide','P','int') ? 1 : 0);
					if( $comment['pid'] == 0 && !ican('post_comment')) {
						$errmsg[] = '你所在的用户组没有发表留言的权限。';
					}
					if ( $comment['pid'] > 0 && !ican('reply_comment') ) {
						$output['type'] = 'error';
						$output['data'] = '抱歉，你所在用户组没有回复留言的权限。';
						exit(json_encode($output));
					}
					//检查与上次留言时间间隔
					$last_time = getGP('last_comment_time','c');
					$comment_time_limit = ican('comtimelimit');
					if ($last_time && (TIMESTAMP - $last_time) < $comment_time_limit) {
						$errmsg[] = '你的留言速度太快了，'.($comment_time_limit - (TIMESTAMP - $last_time)).'秒后再发吧。';
					}
					if ( ican('comneedcode') && !ISADMIN ) {
						session_start();
						$vdcode = getGP('vdcode','P');
						if ($vdcode != $_SESSION['vdcode']) {
							$errmsg[] = '验证码错误。';
							unset($_SESSION['vdcode']);
						}
					}
					if (!$comment['referid'] && !$comment['shopid']) {
						$errmsg[] = '非法请求。';
					} else {
//						$status = $_G['db']->result("SELECT allowreply FROM ".table("shops")." WHERE  shopid = '$comment[referid]'");
//						//文章权限，未加入好友查检
//						if ($status == 0) {
//							$errmsg[] = '该商家不允许留言。';
//						} else{
//							
//						}
					}
					if ( $_G['uid'] ) {
						$comment['uid'] = $_G['uid'];
						$comment['username'] = $_G['username'];
						$comment['email'] = $_G['users']['email'];
					} else {
						if (empty($comment['username'])) {
							$errmsg[] = '请填写你的昵称。';
						} elseif (!is_username($comment['username']) || is_banname($comment['username'])) {
							$errmsg[] = '用户名中含有非法字符或系统禁用关键字。';
						}
						if (empty($comment['email'])) {
							$errmsg[] = '请输入你的邮箱地址。';
						} elseif (!is_email($comment['email'])) {
							$errmsg[] = '你输入的邮箱地址不合法。';
						} elseif ($_G['db']->result("SELECT uid FROM ".table("users")." WHERE email = '".$comment['email']."'")) {
							$errmsg[] = '您输入的邮箱地址是本站会员所有，如果你是该用户，请先登录后再留言。';
						}
						if ($_G['db']->result("SELECT uid FROM ".table("users")." WHERE username = '".strtolower($comment['username'])."'")) {
							$errmsg[] = '您输入的昵称是本站会员，但是你还没有登录，如果你是该用户，请先登录后再留言。';
						}
					}
					if (empty($comment['content'])) {
						$errmsg[] = '请输入留言内容。';
					} elseif (!ISADMIN && strlen($comment['content']) > (int)$_G['usergroup']['access']['commaxchars'] ) {
						$errmsg[] = '内容不能超过'.$_G['usergroup']['access']['commaxchars'].'字节，当前的内容长度为'.strlen($comment['content']).'字节。';
					}
					if ($_G['db']->result("SELECT cid FROM ".table("comment")." WHERE username = '$comment[username]' AND content = '$comment[content]' ORDER BY cid DESC LIMIT 0,1")) {
						$errmsg[] = '您似乎已经提交过这条留言了。';
					}
					if (count($errmsg)) {
						$output['type'] = 'error';
						$error = '';
						$i = 0;
						foreach ($errmsg as $msg) {
							$i ++;
							$error .= $i.'.'.$msg."\n";
						}
						$output['data'] = $error;
					} else {
						$comment['dateline'] = $_G['timestamp'];
						$comment['ip'] = $_G['ip'];
						$comment['status'] = ($_G['usergroup']['access']['comneedcheck'] ? 0 : 1);
						$cid = $_G['db']->insert('comment', $comment);
						
						//记录回复时间
						set_cookie('last_comment_time',$_G['timestamp']);
						
						if ( $comment['status'] ) {
							$_G['db']->query("UPDATE ".table("article")." SET comments = comments + 1 WHERE aid = '$comment[referid]'");
						} else {
							$comment['content'] = '<em>你的留言需要管理员审核后才能显示，请耐心等待。</em><br />'.$comment['content'];
						}
						//删除缓存页面
						$article = $_G['db']->fetch('article','*',array('aid'=>$comment['referid']));
	        			$_G['cache']->set($comment['referid'],$article,'article');
						
	        			$query = $_G['db']->query("SELECT c.* FROM ".table('comment')."c WHERE c.referid='".$comment['referid']."' AND c.type=0");
						while($row = $_G['db']->fetch_array($query)) {
							$comment_cache[$row['cid']] = $row;
						}
			        	foreach($comment_cache as $k => $v){
			        		if($v['pid'] > 0){
			        			$comment_cache[$v['pid']]['subcomment'][$v['cid']] = $v;
			        			$comment_cache[$k] = null;
			        			unset($comment_cache[$k]);
			        		}
			        	}
			        	$_G['cache']->set($comment['referid'],$comment_cache,'comment');
						
						//AJAX输出内容
						$output['type'] = 'success';
						$comment['posttime'] = gdate('Y-m-d H:i',$comment['dateline']);
						$output['pid'] = $comment['pid'];
						$listorder=count($comment_cache);
						
						if($comment['pid'] > 0) {
							$themurl=THEME_URL;
							$comment_html = <<<EOT
							<div class="replay"><div class="reply_title"><img width="50" height="50" src="{$themurl}images/50.jpg">
							<strong>{$comment[username]}</strong>   <span class="reply_time">{$comment['posttime']}</span> </div><div class="reply_content">{$comment[content]}</div></div>
EOT;
						}else{
						$comment_html = <<<EOT
							<li id="comment-{$cid}">
							<div class="comment_title">
								<a name="comment-{$cid}">{$listorder}.</a>
								<strong>{$comment[username]}</strong><span class="comment_time">{$comment['posttime']} <a onclick="reply_comment({$cid});return false;" href="#comment-{$cid}">回复</a></span>
							</div>
							<div class="comment_content">{$comment[content]}<span class="end"></span></div>
							
							</li>
EOT;
						}
						$output['data'] = $comment_html;
						
					}
					exit(json_encode($output));
				break;
				
		}
	}


}	